import axios from "axios";
import qs from "qs";
import env from "./env";

function goLogin() {
  localStorage.removeItem("token");
  const uri = encodeURIComponent(location.href);
  setTimeout(() => {
    location.replace(`/#/login?return=${uri}`);
  });
}

axios.interceptors.request.use(
  (config: any) => {
    if (!env.enableProxy && !/^http:\/\//.test(config.url)) {
      config.url = `${env.apiHost}${config.url}`;
    }

    // POST前，对数据重组成form格式

    if (!/application\/json/.test(config.headers["Content-Type"]) && config.headers["Content-Type"] !== "multipart/form-data") {
      config.transformRequest = (data: any) => {
        return qs.stringify(data);
      };
    }

    /**
     * 如果不想添加Authorization标识，请在接口参数传入{token: false}
     */
    const data = config.data ? config.data : config.params;
    const token = localStorage.getItem("token");
    // if (token && ((!config.data || config.data.token !== false) || (!config.params || config.params.token !== false))) {
    if (token && (!data || data.token !== false)) {
      config.headers.Authorization = "Bearer " + token;
    }

    if (config.data && config.data.token !== void 0) {
      delete config.data.token;
    }

    if (config.params && config.params.token !== void 0) {
      delete config.params.token;
    }

    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response: any) => {
    if (response.status === 200) {
      if (response.data.code === 401) {
        goLogin();
      } else {
        return response.data;
      }
    } else {
      return Promise.reject(response);
    }
  },
  (error: any) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          goLogin();
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default axios;
